package cn.mdmbct.douyin.common.redis;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * RedisTemplate实现redis操作
 *
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/9 15:10
 * @modified mdmbct
 * @since 1.0
 */
@RequiredArgsConstructor
public class RedisTemplateOps implements DyRedisOps {

    private final StringRedisTemplate redisTemplate;

    @Override
    public <T> T getValue(String key, Class<T> valueClass) {
        return JSONObject.parseObject(redisTemplate.opsForValue().get(key), valueClass);
    }

    @Override
    public <T> void setValue(String key, T value, long expire, TimeUnit timeUnit) {
        if (expire <= 0) {
            setValue(key, value);
        } else {
            redisTemplate.opsForValue().set(key, JSONObject.toJSONString(value), expire, timeUnit);
        }
    }

    @Override
    public <T> void setValue(String key, T value) {
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(value));
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    @Override
    public void setExpire(String key, long expire, TimeUnit timeUnit) {
        redisTemplate.expire(key, expire, timeUnit);
    }

}
